package com.zzusedating.androidapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.zzusedating.androidapp.adapters.RecommendRecAdapter;
import com.zzusedating.androidapp.customlayout.TextViewWithRightText;
import com.zzusedating.androidapp.tools.BasicCallback;
import com.zzusedating.androidapp.tools.ConstantsTools;
import com.zzusedating.androidapp.tools.MyApplication;
import com.zzusedating.androidapp.tools.ZodiacUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;


public class UserInfoActivity extends BaseActivity {
    private static final String TAG = "UserInfoActivity";
    private static final int USER_NOT_FOUND_I = 5;
    private static final int GET_USER_INFO_SUCCESS_I = 1;
    private static final String USER_NOT_FOUND_ = "用户不存在";

    private static final Integer followed = 1;
    private static final Integer unfollowed = 0;

    private int userId;

    private Callback callback, leaveCallback;
    private Handler handler;

    private CircleImageView headView;
    private TextView nameView;
    private TextView levelView;
    private TextView followView;
    private TextView followerView;
    private TextView popView;
    private TextView activeView;
    private TextView prizeView;
    private TextView selfDescView;
    private TextViewWithRightText activeDayView;
    private TextViewWithRightText maritalView;
    private TextViewWithRightText vMoneyView;
    private TextViewWithRightText birthView;
    private TextViewWithRightText residentView;
    private TextViewWithRightText eduBgView;
    private TextViewWithRightText majorView;
    private TextViewWithRightText heightView;
    private TextViewWithRightText weightView;
    private TextViewWithRightText constellationView;
    private TextViewWithRightText orgTypeView;
    private TextViewWithRightText monthlySalaryView;
    private TextViewWithRightText emailView;
    private Button followButton;
    private Button leaveMessageButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_layout);

        userId = getIntent().getIntExtra(RecommendRecAdapter.USER_ID_EXTRA, -1);
        if (userId == -1) {
            MyApplication.Toast(ConstantsTools.NETWORK_ERROR_);
            return;
        }

        initCallback();

        headView = findViewById(R.id.She_Head);
        nameView = findViewById(R.id.She_Name);
        levelView = findViewById(R.id.She_Level);
        followView = findViewById(R.id.She_Follow);
        followerView = findViewById(R.id.She_Fans);
        popView = findViewById(R.id.She_Pop);
        activeView = findViewById(R.id.She_Active);
        prizeView = findViewById(R.id.She_Prize);
        selfDescView = findViewById(R.id.She_SelfDesc);
        activeDayView = findViewById(R.id.She_ActiveDay);
        maritalView = findViewById(R.id.She_Marry);
        vMoneyView = findViewById(R.id.She_VMoney);
        birthView = findViewById(R.id.She_Birth);
        residentView = findViewById(R.id.She_Residence);
        eduBgView = findViewById(R.id.She_EduBg);
        majorView = findViewById(R.id.She_Major);
        heightView = findViewById(R.id.She_Height);
        weightView = findViewById(R.id.She_Weight);
        constellationView = findViewById(R.id.She_Constellation);
        orgTypeView = findViewById(R.id.She_OrgType);
        monthlySalaryView = findViewById(R.id.She_MonthlySalary);
        followButton = findViewById(R.id.She_FollowButton);
        leaveMessageButton = findViewById(R.id.She_LeaveMessageButton);
        emailView = findViewById(R.id.She_Email);

        followButton.setTag(unfollowed);
        initListener();

        MyApplication.getClient().newCall(new Request.Builder()
                .get()
                .url(String.format(ConstantsTools.GET_SHE_ALL_INFO, userId))
                .build()
        ).enqueue(callback);
    }

    private void setUserInfo(JSONObject detail, JSONObject info, boolean following) {
        try {
            if (following) {
                followButton.setText("取关");
                followButton.setTag(followed);
            }
            nameView.setText(info.getString("name"));
            levelView.setText(String.format("Lv.%s", info.getString("vipLevel")));
            followView.setText(String.format("关注 %s", info.getString("followNum")));
            followerView.setText(String.format("粉丝 %s", info.getString("fansNum")));
            popView.setText(String.format("人气 %s", info.getString("popularity")));
            activeView.setText(String.format("活跃值 %s", info.getString("activeValue")));
            prizeView.setText(String.format("赞 %s", info.getString("praisedNum")));
            selfDescView.setText(info.getString("selfIntro"));
            activeDayView.setRightText(info.getString("activeDays"));
            maritalView.setRightText(getResources().
                    getStringArray(R.array.marry_status_list)[info.getInt("maritalStatus") - 1]);
            vMoneyView.setRightText(info.getString("coins"));
            birthView.setRightText(info.getString("birthday"));
            emailView.setRightText(info.getString("email"));
            residentView.setRightText(detail.getString("domicile"));
            eduBgView.setRightText(getResources().getStringArray(R.array.edu_bg_list)[detail.getInt("education")]);
            majorView.setRightText(detail.getString("major"));
            heightView.setRightText(detail.getInt("height"));
            weightView.setRightText(detail.getInt("weight"));
            constellationView.setRightText(ZodiacUtil.date2Constellation(info.getString("birthday")));
            orgTypeView.setRightText(getResources().
                    getStringArray(R.array.org_type_list)[detail.getInt("organizationType")]);
            monthlySalaryView.setRightText(detail.getInt("monthlySalary"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initListener() {
        followButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyApplication.getClient().newCall(
                        new Request.Builder()
                                .get()
                                .url(String.format(ConstantsTools.FOLLOW_UN_USER, userId))
                                .build()
                ).enqueue(leaveCallback);

            }
        });
        leaveMessageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserInfoActivity.this, LeaveMsgActivity.class);
                intent.putExtra("userId", userId);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void initCallback() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case GET_USER_INFO_SUCCESS_I:
                        JSONObject jsonObject = (JSONObject) msg.obj;
                        try {
                            setUserInfo(jsonObject.getJSONObject("details"),
                                    jsonObject.getJSONObject("info"), jsonObject.getBoolean("following"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    case 15:
                    case USER_NOT_FOUND_I:
                        MyApplication.Toast(USER_NOT_FOUND_);
                        break;
                    case 9:
                        MyApplication.Toast("用户未登录");
                        break;
                    case 11:
                        if (followButton.getTag() == followed) {
                            MyApplication.Toast("已取消关注");
                            followButton.setText(getString(R.string.follow));
                            followButton.setTag(unfollowed);
                        } else {
                            MyApplication.Toast("已关注");
                            followButton.setText(getString(R.string.no_follow));
                            followButton.setTag(followed);
                        }
                        break;
                }
                return true;
            }
        });
        callback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendMessage(ConstantsTools.createMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200) {
                    Log.e(TAG, "onResponse: code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1) {
                        handler.sendMessage(ConstantsTools.createMessage
                                (GET_USER_INFO_SUCCESS_I, jsonObject.getJSONObject("data")));
                    } else {
                        if (jsonObject.getInt("code") == 5)
                            handler.sendMessage(ConstantsTools.createMessage(USER_NOT_FOUND_I));
                        else
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        leaveCallback = new BasicCallback(handler) {
            @Override
            public void onResponse(Call call, @NonNull Response response) {
                handler.sendMessage(ConstantsTools.createMessage(getStatus(response) + 10));
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK)
                    MyApplication.Toast("留言成功");
                else if (resultCode != RESULT_CANCELED)
                    MyApplication.Toast(ConstantsTools.NETWORK_ERROR_);
        }
    }
}
